package com.androidRtc.dao;

import com.androidRtc.entity.Room;
import com.androidRtc.util.JdbcUtil;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class RoomDao {

    JdbcUtil util = new JdbcUtil();

    public int add(Room room){
        String sql = "insert into room(RoomName,Rpassword,creater) values(?,?,?)";
        String sql2 = "select ID from room where RoomName = ? ";
        PreparedStatement ps = util.createStatement(sql);
        PreparedStatement ps2 = util.createStatement(sql2);
        ResultSet rs = null;
        Integer ID = 0;
        int result = 0;
        try {
            ps.setString(1,room.getRoomName());
            ps.setString(2,room.getRpassword());
            ps.setString(3,room.getCreater());
            result = ps.executeUpdate();
            if(result == 1){
                ps2.setString(1,room.getRoomName());
                rs = ps2.executeQuery();
                while (rs.next()){
                    ID = rs.getInt("ID");
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally{
            util.close();
        }
        return ID;
    }

    public int login(String RoomName,String Rpassword){
        String sql = "select count(*) from room where RoomName = ? and Rpassword = ?";
        PreparedStatement ps = util.createStatement(sql);
        ResultSet rs = null;
        int result = 0;
        try {
            ps.setString(1,RoomName);
            ps.setString(2,Rpassword);
            rs = ps.executeQuery();
            while(rs.next()){
                result = rs.getInt("count(*)");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            util.close(rs);
        }
        return result;
    }

    public List findAll(){
        String sql = "select * from room";
        PreparedStatement ps = util.createStatement(sql);
        ResultSet rs = null;
        List<Room> list = new ArrayList<Room>();
        try {
            rs = ps.executeQuery();
            while(rs.next()){
                Integer ID = rs.getInt("ID");
                String RoomName = rs.getString("RoomName");
                String Rpassword= rs.getString("Rpassword");
                String creater = rs.getString("creater");
                Room room = new Room(ID,Rpassword,RoomName,creater);
                list.add(room);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            util.close(rs);
        }
        return list;
    }


}
